package com.action.app_noverify;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;

import com.cache.TimeOutNetOperate;
import com.cache.TimeoutNetEntity;
import com.dataProcess.MapPart;
import com.dataProcess.NetConnect;
import com.dataProcess.Noverify;
import com.enetiy.Area;
import com.enetiy.Binding;
import com.enetiy.Comboinfo;
import com.enetiy.Nettimeout;
import com.enetiy.Useraccount;
import com.enetiy.Userinfo;
import com.enetiy.Users;
import com.operation.Cache;
import com.operation.GateIP;
import com.operation.HotspotLink;
import com.operation.NET;
import com.service.AreaIpService;
import com.service.AreaService;
import com.service.AreainfoService;
import com.service.AreausbleService;
import com.service.BindingService;
import com.service.ComboService;
import com.service.DealService;
import com.service.LoginService;
import com.service.MapService;
import com.service.NetLinkService;
import com.service.UseraccountService;
import com.service.UserinfoService;
import com.threads.NetMapThread;
import com.threads.NetoutThread;
import com.util.DataUtil;
import com.util.IPUtil;
import com.util.Log4gUtil;
import com.util.NetTimeUtil;
import com.util.RandomUtil;
import com.util.Verify;

public class NoverifyNetAction {
	private UserinfoService  userinfoService;
	private ComboService comboService;
	private AreaService areaService;
	private BindingService bindingService;
	private AreausbleService areausbleService;
	private AreaIpService areaIpService;
	private NetLinkService netLinkService;
	private AreainfoService areainfoService;
	private UseraccountService useraccountService;
	private LoginService loginService;
	private DealService dealService;
	private MapService mapService;
	
	private NET nets = new NET();
	
	private String apMac;
	private String apName;
	private String nasid;
	private int visitType;
	private int planTime;
	private String openId;
	private String auditAccount;
	
	private int siteAreaid;
	private String ip;
	private String userMac;
	private String params;
	private int userid;
	private String NF_callid;
	private String token;
	private String areaIden;
	private int code;
	private int result;


	
	private int getSiteAreaid() throws Exception{
		int areaid = siteAreaid;
		if((apMac!=null&&!apMac.equals("")&&!apMac.equals("null"))||
				(apName!=null&&!apName.equals("")&&!apName.equals("null"))||
				(nasid!=null&&!nasid.equals(""))&&!nasid.equals("null")){
			MapPart mp = new MapPart();
			Log4gUtil.Info("getSiteAreaid-", userid+"", "进入连网param&area:"+siteAreaid, "apName--"+apName+"--apMac--"+apMac+"--nasid--"+nasid, NF_callid, token);
			areaid = mp.getAreaId(mapService, 0, apName, 10000, "", apMac, nasid);
		}
		return areaid;
	}
	
	/**
	 * 
	 * 无感知连网  >Nf010
	 */
	
	public void noFeelNet(){
		if(params!=null&&!params.equals("")){
			org.json.JSONObject dataParser = DataUtil.dataParser(params);
			if(dataParser.has("ip"))
				ip = dataParser.getString("ip");
			if(dataParser.has("userMac"))
				userMac = dataParser.getString("userMac");
			if(dataParser.has("apMac"))
				apMac = dataParser.getString("apMac");
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		int connect =2;//网络连接状态
		JSONObject json = DataUtil.sendJson();
		try {
			if(siteAreaid==10000||siteAreaid==10005)
				siteAreaid = getSiteAreaid();//获取准确区域id
			Log4gUtil.Info("noFeelNet-无感知连网", userid+"","进入param", params+siteAreaid, NF_callid, token);
			out=response.getWriter();
			Userinfo  userinfo = null;
			Area siteArea=null;
			NetConnect netConnect =new NetConnect(connect);
			if((userinfo = userinfoService.selectUserMac(userMac)) != null&&
					userinfo.getAppOnline()==1 && siteAreaid !=0){
				String gateIp = areaIpService.selectAreaip(siteAreaid).getPublicIp();
				if(siteAreaid!=2){
					List<Useraccount> accounts = useraccountService.selectUseraccounts(userinfo.getUsers().getId(), 1);
					if(!accounts.isEmpty()){
						netConnect.getNetConnect(userinfo, siteArea, ip, gateIp, userMac,accounts.get(0).getAccount(),1, comboService, 
								areainfoService, bindingService, areausbleService,userinfoService,dealService,NF_callid,token,
								apMac,mapService,netLinkService);
					}
				}else{
					Binding binding = bindingService.selectbinding(userinfo.getUsers().getId(), siteAreaid);
					if(binding!=null&&binding.getTypeExplain().equals("老师")){
						List<Useraccount> accounts = useraccountService.selectUseraccounts(userinfo.getUsers().getId(), 1);
						if(!accounts.isEmpty()){
							Log4gUtil.Info("noFeelNet-无感知连网", userinfo.getUsers().getId()+"","深职院","老师"+accounts.get(0).getAccount()+"--"+dealService, NF_callid, token);
							netConnect.getNetConnect(userinfo, siteArea, ip, gateIp, userMac,accounts.get(0).getAccount(),1, comboService, 
									areainfoService, bindingService, areausbleService,userinfoService,dealService,NF_callid,token,
									apMac,mapService,netLinkService);
						}
					}
				}
			}
			json.put("code", 1);
			json.put("connect", netConnect.connect);
			Log4gUtil.Info("noFeelNet-无感知连网", userid+"","输出", json.toString(), NF_callid, token);
		} catch (Exception e) {
			json.put("code", -1);
			e.printStackTrace();
		}
		out.print(json);
	}
	
	
	/**
	 * 
	 * 临时连接网络 >Nf012
	 */
	public void tempNet(){
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		JSONObject json = DataUtil.sendJson();
		try {
			out=response.getWriter();
			if(params!=null&&!params.equals("")){
				org.json.JSONObject dataParser = DataUtil.dataParser(params);
				if(dataParser.has("ip"))
					ip = dataParser.getString("ip");
				if(dataParser.has("userMac"))
					userMac = dataParser.getString("userMac");
				if(dataParser.has("siteAreaid"))
					siteAreaid = dataParser.getInt("siteAreaid");
				if(dataParser.has("userid"))
					userid = dataParser.getInt("userid");
				if(dataParser.has("visitType"))
					visitType =dataParser.getInt("visitType");
				if(dataParser.has("planTime"))
					planTime =dataParser.getInt("planTime");
				if(dataParser.has("auditAccount"))
					auditAccount = dataParser.getString("auditAccount");
			}
			if(auditAccount==null){
				auditAccount = "";
			}
			Userinfo userinfo = userinfoService.selectUserinfo(userid);
		if(userinfo==null){
			userid = Integer.parseInt(RandomUtil.getRandomShuzi(9));
		}else{
			Useraccount account = useraccountService.selectUseraccount(userid, 1);
			auditAccount = account.getAccount();
		}
		Area sitearea;
			if(siteAreaid==10000||siteAreaid==10005)
				siteAreaid = getSiteAreaid();//获取准确区域id
			Log4gUtil.Info("tempNet-临时连网", userid+"", "param", params, NF_callid, token);
			
			String gateIp = areaIpService.selectAreaip(siteAreaid).getPublicIp();
			sitearea = areaService.selectArea(siteAreaid);
			
			
			int net=0;
			if(sitearea!=null) {
				String shichang = NetTimeUtil.getTimeUtil(new Date(), IPUtil.getLingshilianwang());
				if(planTime!=0){
					shichang = NetTimeUtil.getTimeUtil(new Date(), planTime);
				}
				 net = nets.netAllow("","", siteAreaid, ip, 2, sitearea.getNetOnline(),
						 shichang, gateIp, userid,userMac, auditAccount,4,1,NF_callid,token,
						apMac,"",mapService,areausbleService,netLinkService);
				 if(net==1){
					 if(userinfo!=null){
						userinfo.setUserMac(userMac);
						userinfo.setUserIp(ip);
						userinfo.setArea(sitearea);
						userinfoService.updateUserinfo(userinfo);
					}
					//portal临时放行加入缓存
					if(visitType==2&&ip!=null&&!ip.equals("")){
						HashMap<String, String> tempnetMap = Cache.getCache().getTempnetMap();
						tempnetMap.put(ip,new Date().getTime() +"_"+userMac+"_"+siteAreaid+"_"+userid);
					}
				 }
			}
			json.put("code", 1);
			json.put("connect", net);
		} catch (Exception e) {
			json.put("code", -1);
			e.printStackTrace();
		}
		Log4gUtil.Info("tempNet-临时连网", userid+"", "输出", json.toString(), NF_callid, token);
		out.print(json);
	}
	
	
	
	
	
	/**
	 * 微信登入网络
	 */
	public  void  weixinEnrollNet(){
		if(params!=null&&!params.equals("")){
			org.json.JSONObject dataParser = DataUtil.dataParser(params);
			if(dataParser.has("openId"))
				openId = dataParser.getString("openId");
			if(dataParser.has("siteAreaid"))
				siteAreaid = dataParser.getInt("siteAreaid");
			if(dataParser.has("userMac"))
				userMac = dataParser.getString("userMac");
			if(dataParser.has("ip"))
				ip = dataParser.getString("ip");
		}
		
		Log4gUtil.Info("weixinEnrollNet", userid+"", "进入自动登录param", params, NF_callid, token);
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		JSONObject json = DataUtil.sendJson();
		try {
			out=response.getWriter();
			//如请求为代理服务请求, 存储其公网地址
			Userinfo userinfo = null;
			Users user = null;
			if(openId!=null&&!openId.equals("")){
					Useraccount useraccount = useraccountService.selUseraccountOpenId(openId);
					if(useraccount!=null){
						userinfo = userinfoService.selectUserinfo(useraccount.getUsers().getId());
						user = useraccount.getUsers();
					}else{
						//默认头像路劲
						String realPath = IPUtil.getFilePath()+"/img/uersImg/headImg/MoRenHead/";
						File f = new File(realPath);
						//路劲底所有图片
						String[] list = f.list();
						String headimg ="";
						if(list!=null)
							headimg ="MoRenHead/"+list[0];
						user = new Users();
						user.setPwd("");
						user.setFirstlogin(new Date());
						user.setNickname("未录入");
						user.setHeadImg(headimg);
						user.setSex(1);
						//添加用户
						Serializable usersid = loginService.insertUsers(user);
						user.setId(Integer.parseInt(usersid.toString()));
						
						//缓存token
						userinfo = new Userinfo();
						userinfo.setToken(usersid+"wqwq");//更新token
						userinfo.setUsers(user);
						userinfo.setAppOnline(1);
						userinfo.setUserMac(userMac);
						userinfo.setUserIp(ip);
						//添加用户信息
						userinfoService.insertUserinfo(userinfo);
						
						//用户账号信息
						useraccount = new Useraccount();
						useraccount.setAccount("");//账号
						useraccount.setStatus(1);//账号状态(1:可以使用,0:不可以使用)
						useraccount.setAccountype(2);//账号类型(1:手机,2:微信 )
						useraccount.setWeixinOpen(openId);
						useraccount.setUsers(user);//所属用户
						//添加账号
						useraccountService.insetrUseraccount(useraccount);
					}
					
					Thread.sleep(1000);
					//连网
					Area area = areaService.selectArea(siteAreaid);
					if(area!=null){
						HttpServletRequest request = ServletActionContext.getRequest();
						String gateIp = GateIP.getIP(request);
						//下线
						MapPart mapPart = new MapPart();
						int netState = 0;
						netState = mapPart.cacheOutNet(ip, areaIpService, netState);
						//上线
						int netAllow = nets.netAllow("", "", siteAreaid, ip, 6, area.getNetOnline(), NetTimeUtil.getTimeUtil(new Date(), 180),
								gateIp, user.getId(), userMac, openId, 2,1 ,NF_callid , token, apMac,"" ,mapService, areausbleService, netLinkService);
						if(netAllow==1){
							userinfo.setArea(area);
							userinfo.setUserMac(userMac);
							userinfo.setUserIp(ip);
							userinfoService.updateUserinfo(userinfo);
						}
						json.put("code", 1);
						json.put("connect", netAllow);
					}else{
						json.put("code", 0);
						json.put("msg", "区域不存在");
					}
				}else{
					json.put("code", 0);
					json.put("msg", "openid为空");
				}
			} catch (Exception e) {
				json.put("code", -1);
				json.put("msg", "服务器异常");
				e.printStackTrace();
			}
		out.print(json);
		Log4gUtil.Info("weixinEnrollNet", userid+"", "进入自动登录param", params, NF_callid, token);
	}
	
	/**
	 * 轮循连网  >Nf066
	 */
	public void  roundNet(){
		org.json.JSONObject data = DataUtil.dataParser(params);
		if(params!=null&&!params.equals("")){
			if(data.has("areaIden"))
				areaIden = data.getString("areaIden");
		}
		Log4gUtil.Info("roundNet-轮循连网", userid+"", "params", params, NF_callid, token);
			
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		JSONObject sendjson = DataUtil.sendJson();
		try {
			
			List<Nettimeout> timeoutList = netLinkService.selectNettimeoutList(areaIden);
			for (int i = 0; i < timeoutList.size(); i++) {
				Nettimeout nettimeout = timeoutList.get(i);
				long time = nettimeout.getSetTime().getTime();
				long time2 = new Date().getTime();
				if((time2-time)>120000){
					timeoutList.remove(i);
					netLinkService.delNettimeout(nettimeout);
				}
			}
			
			JSONArray topList = new JSONArray(timeoutList);
			out = response.getWriter();
			sendjson.put("code", 1);
			sendjson.put("timeout",topList);

		} catch (Exception e) {
			sendjson.put("code", -1);
			e.printStackTrace();
		}
		out.print(sendjson);
		Log4gUtil.Info("roundNet-轮循连网", userid+"", "输出", sendjson.toString(), NF_callid, token);
	}
	
	
	/**
	 * 删除超时指令 >Nf067
	 */
	public void delRoundNet(){
		org.json.JSONObject data = DataUtil.dataParser(params);
		if(params!=null&&!params.equals("")){
			if(data.has("userid"))
				userid=data.getInt("userid");
			if(data.has("ip"))
				ip=data.getString("ip");
			if(data.has("code"))
				code = data.getInt("code");
		} 
		try {
			if(code==1){
				List<Nettimeout> timeout = netLinkService.selectNettimeoutList(userid, ip);
				if(!timeout.isEmpty()){
					Nettimeout nettimeout = timeout.get(0);
					NetMapThread netMapThread = new NetMapThread(mapService, nettimeout.getApMac(), 
							nettimeout.getUserid(), nettimeout.getAreaid(), nettimeout.getDuration(), nettimeout.getServerType(),nettimeout.getIp(),nettimeout.getMac(),nettimeout.getNetOrder());
					Thread thread1 = new Thread(netMapThread);
					thread1.start();
				}
			}
			Noverify noverify = new Noverify();
			noverify.delNettimeout(netLinkService, ip, userid);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setUserinfoService(UserinfoService userinfoService) {
		this.userinfoService = userinfoService;
	}
	public void setUserMac(String userMac) {
		this.userMac = userMac;
	}
	public void setComboService(ComboService comboService) {
		this.comboService = comboService;
	}
	public void setSiteAreaid(int siteAreaid) {
		this.siteAreaid = siteAreaid;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public void setBindingService(BindingService bindingService) {
		this.bindingService = bindingService;
	}


	public void setAreainfoService(AreainfoService areainfoService) {
		this.areainfoService = areainfoService;
	}

	public void setAreausbleService(AreausbleService areausbleService) {
		this.areausbleService = areausbleService;
	}

	public void setUseraccountService(UseraccountService useraccountService) {
		this.useraccountService = useraccountService;
	}


	public void setParams(String params) {
		this.params = params;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}
	public void setNF_callid(String nF_callid) {
		NF_callid = nF_callid;
	}

	public void setDealService(DealService dealService) {
		this.dealService = dealService;
	}

	public void setAreaIpService(AreaIpService areaIpService) {
		this.areaIpService = areaIpService;
	}


	public void setToken(String token) {
		this.token = token;
	}


	public void setAreaIden(String areaIden) {
		this.areaIden = areaIden;
	}


	public void setCode(int code) {
		this.code = code;
	}


	public void setNetLinkService(NetLinkService netLinkService) {
		this.netLinkService = netLinkService;
	}


	public void setMapService(MapService mapService) {
		this.mapService = mapService;
	}


	public void setApMac(String apMac) {
		this.apMac = apMac;
	}


	public void setApName(String apName) {
		this.apName = apName;
	}


	public void setNasid(String nasid) {
		this.nasid = nasid;
	}


	public void setResult(int result) {
		this.result = result;
	}

	public void setVisitType(int visitType) {
		this.visitType = visitType;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	public void setOpenId(String openId) {
		this.openId = openId;
	}

	public void setPlanTime(int planTime) {
		this.planTime = planTime;
	}
	
}
